var session = require('./session');
var mysql = require('../sys/mysql');

//全局变量保存所有session，当不使用内存存储时，此全局变量无作用，注意开启多进程时内存同步问题
if (!global.sessions) {
    global.sessions = Object.create(null);
}

//当配置session保存在mysql数据库中时，若指定session表不存在则在启动时自动创建
if (sysConfig.session.store == 'mysql') {
    mysql.execSync(`
        CREATE TABLE IF NOT EXISTS \`${sysConfig.session.table}\` (
            \`njsid\` varchar(255) NOT NULL COMMENT '键',
            \`session\` varchar(8000) DEFAULT NULL COMMENT '值',
            \`update\` datetime DEFAULT NULL COMMENT '更新时间',
            PRIMARY KEY (\`njsid\`)
        ) ENGINE=MEMORY DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT '会话表';
    `);
}

module.exports = {
    read: function (njsid, callback) {
        if (sysConfig.session.store == 'mysql') {
            mysql.exec('SELECT session FROM `' + sysConfig.session.table + '` WHERE njsid = {njsid};UPDATE `' + sysConfig.session.table + '` SET `update` = {update} WHERE njsid = {njsid}', {
                njsid: njsid,
                update: new Date().toDate('yyyy-MM-dd hh:mm:ss')
            }, function (err, rows) {
                var sess = new session();
                if (err || rows[0].length == 0) {
                    callback(sess);
                } else {
                    var s = JSON.parse(rows[0][0].session);
                    sess._session = s._session;
                    callback(sess);
                }
            });
        } else {
            if (!global.sessions[njsid])
                global.sessions[njsid] = new session();
            global.sessions[njsid].updateTime = new Date();
            callback(global.sessions[njsid]);
        }
    },

    store: function (njsid, value, callback) {
        if (sysConfig.session.store == 'mysql') {
            mysql.exec('INSERT INTO `' + sysConfig.session.table + '`(njsid, session, `update`) VALUES({njsid}, {value}, {update}) ON DUPLICATE KEY UPDATE session = {value}, `update` = {update}', {
                njsid: njsid,
                value: value,
                update: new Date().toDate('yyyy-MM-dd hh:mm:ss')
            }, function () {
                callback();
            });
        } else {
            global.sessions[njsid] = value;
            callback();
        }
    },

    autoClear: function () {
        if (sysConfig.session.store == 'mysql') {
            mysql.exec('DELETE FROM `' + sysConfig.session.table + '` WHERE `update` < {update}', {
                update: (new Date() - sysConfig.session.timeout).toDate('yyyy-MM-dd hh:mm:ss')
            }, function () {});
        } else {
            for (var prop in global.sessions) {
                if (new Date() - global.sessions[prop].updateTime > sysConfig.session.timeout) {
                    delete global.sessions[prop];
                }
            }
        }
    }
};